package com.list88zhu.android.sunflower.http;

import android.support.v4.util.ArrayMap;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import retrofit2.Retrofit;

/**
 * <pre><code>
 *
 *  </code></pre>
 *
 * @author zhuyingming@qmtv.com
 * @date 2018/9/9
 */
public class ApiProxy {

    private Lock lock = new ReentrantLock();
    private Retrofit retrofit;
    private final ArrayMap<Class, Object> cache;

    public ApiProxy(Retrofit retrofit) {
        this.retrofit = retrofit;
        cache = new ArrayMap<>();
    }

    /**
     * Call<NewsLatestBean> call = retrofit.create(ZhihuApi.class).getNewsLatest();
     */
    public <T> T create(Class<T> serviceCls) {
        Object serviceApi = cache.get(serviceCls);
        if(serviceApi == null) {
            lock.lock();
            serviceApi = retrofit.create(serviceCls);
            cache.put(serviceCls, serviceApi);
            lock.unlock();
        }
        return (T) serviceApi;
    }
}
